<template>
    <div class="box-content">
        <div class="navigation">用户管理/<span class="check-children" @click="$router.go(-1)">账户列表</span>/子账户列表</div>
        <!--搜索-->
        <div class="mt-3">
            <el-form ref="searchForm" :inline="true" :model="searchForm" class="search-form">
                <el-form-item>
                    <el-input
                            class=" mrt-10"
                            style="width: 200px;"
                            placeholder="请输入电话关键字"
                            v-model="searchForm.phoneOrName"
                            clearable>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSearch">查询</el-button>
                    <!--<el-button type="success" @click="addChildrenAccount">添加</el-button>-->
                </el-form-item>
            </el-form>
            <el-table
                    :data="userData"
                    v-loading="isLoad"
                    align="center"
                    :header-cell-style="tableHeaderColor"
                    :element-loading-text="loadText"
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        align="center"
                        label="编号"
                        width="100"
                >
                </el-table-column>
                <el-table-column
                        prop="name"
                        align="center"
                        label="昵称"
                >
                </el-table-column>
                <el-table-column
                        prop="phone"
                        align="center"
                        label="手机号"
                        width="150"
                >
                </el-table-column>
                <el-table-column
                        prop="call_seconds"
                        align="center"
                        label="通话时长(分钟)"
                        width="150"
                >
                    <template slot-scope="scope">
                        <div align="center">{{scope.row.call_seconds/60}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="call_times"
                        align="center"
                        label="通话次数"
                        width="150"
                >
                </el-table-column>
                <el-table-column
                        align="center"
                        label="账户状态"
                >
                    <template slot-scope="scope">
                        <div align="center">{{scope.row.status !== 0?'正常':'暂停'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="创建日期"
                        align="center"
                        width="100">
                    <template slot-scope="scope">
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="状态/操作"
                        align="center"
                        fixed="right"
                        width="160"
                >
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="primary"
                                @click="handleEdit(scope.row)">编辑
                        </el-button>
                        <el-button
                                size="mini"
                                type="danger"
                                v-if="scope.row.status == '1'"
                                @click="handleDelete(scope.row)">暂停
                        </el-button>
                        <el-button
                                size="mini"
                                type="success"
                                v-if="scope.row.status == '0'"
                                @click="handleRecovery(scope.row)">恢复
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog
                :title="isEdit?'修改子账号':'添加子账号'"
                :visible.sync="dialogVisible"
                width="600px"
                :close-on-click-modal="false">
            <div class="dialogs" v-loading="isLoadAccount">
                <el-form label-position="right" label-width="80px" :model="formLabelAccount" status-icon :rules="rules"
                         ref="formLabelAccount" style="width: 450px;margin: 0 auto;">
                    <el-form-item label="昵称" prop="nickName">
                        <el-input v-model="formLabelAccount.nickName" placeholder="请输入子账号昵称" type="text"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone" v-if="!isEdit">
                        <el-input v-model="formLabelAccount.phone" placeholder="请输入子账号手机号" type="text"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password" v-if="!isEdit">
                        <el-input v-model="formLabelAccount.password" placeholder="请输入子账号密码"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" v-if="!isEdit" :loading="loading" @click="submitForm('formLabelAccount')">{{loading?'创建中':'点击创建'}}</el-button>
                <el-button type="primary" v-if="isEdit"  :loading="loading" @click="submitForm('formLabelAccount')">{{loading?'修改中':'点击修改'}}</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "createAccount",
        data() {
            var validatePhone = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入手机号'));
                } else {
                    let myreg = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
                    if (!myreg.test(value)) {
                        callback(new Error('请正确输入手机号!'));
                    }
                    callback();
                }
            };
            var validateName = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入昵称'));
                } else {
                    if (value.length > 10) {
                        callback(new Error('昵称小于10个字符'));
                    }
                    callback();
                }
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    var r = /^[^\u4e00-\u9fa5]+$/
                    if (!r.test(value)) {
                        callback(new Error('密码不能为中文!'));
                    }
                    if (value.length < 6) {
                        callback(new Error('密码长度在 6 到 18 个字符!'));
                    }
                    callback();
                }
            };
            return {
                rules: {
                    nickName: [
                        {validator: validateName, trigger: 'change'}
                    ],
                    phone: [
                        {validator: validatePhone, trigger: 'change'}
                    ],
                    password: [
                        {validator: validatePass, trigger: 'change'}
                    ]
                },
                loading: false,
                disabled: false,
                isEdit:false,
                formLabelAccount: {
                    phone: '',
                    password: '',
                    nickName: ''
                },
                searchForm:{
                    phoneOrName: '',
                    roleStatus: ''
                },
                isLoad: false,
                loadText: '数据加载中',
                searchStr: "",//实际查询字符串
                page: 1,
                pageSize: 10,
                totalPage: 0,
                dialogVisible: false,
                isLoadAccount: false,
                userData: [],
                saveAccount:{}
            }
        },
        watch:{
            dialogVisible:function (val) {
                if (!val) {
                    Object.keys(this.formLabelAccount).forEach(key => this.formLabelAccount[key] = '');
                    this.$refs['formLabelAccount'].resetFields();
                }
            }
        },
        created() {
            this.onSearch();
        },
        methods: {
            handleEdit(val) {
                this.isEdit = true;
                this.saveAccount = val;
                this.dialogVisible = true;
                this.isLoadAccount = true;
                this.$http.get('api/admin/common/user/' + val.id)
                    .then((result) => {
                        this.formLabelAccount.phone = result.data.phone,
                            this.formLabelAccount.nickName = result.data.name,
                            this.formLabelAccount.password = result.data.password
                        this.isLoadAccount = false;
                    })
                    .catch((err) => {
                        this.isLoadAccount = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            handleDelete(val) {
                this.$confirm('此操作将暂停账户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = {
                        status: 0
                    };
                    this.$http.put('api/admin/common/user/' + val.id + '?status=0')
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '账号暂停成功!',
                                during:1000
                            });
                            this.getChildrenAccountList();
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleRecovery(val) {
                this.$confirm('此操作将恢复账户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let params = {
                        status: 0
                    };
                    this.$http.put('api/admin/common/user/' + val.id + '?status=1')
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '账号恢复成功!',
                                during:1000
                            });
                            this.getChildrenAccountList();
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            getChildrenAccountList() {
                this.isLoad = true;
                this.$http.get('api/admin/common/childrenList' + this.searchStr, {
                    params: {
                        pageSize: this.pageSize,
                        page: this.page
                    }
                })
                    .then((res) => {
                        this.isLoad = false;
                        this.userData = res.data;
                    })
                    .catch((err) => {
                        this.isLoad = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            addChildrenAccount() {
                this.isEdit = false;
                this.dialogVisible = true;
            },
            submitForm(formName) {
                let _this = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        _this.setChildInfo();
                    } else {
                        return false;
                    }
                });
            },
            setChildInfo() {
                let params;
                this.loading = true;
                if (this.isEdit) {
                    params = {
                        name: this.formLabelAccount.nickName
                    };
                    this.$http.put('api/admin/common/user/'+ this.saveAccount.id, params)
                        .then((result) => {
                            if (result.code == 200) {
                                this.$message.success(result.msg);
                                this.getChildrenAccountList();
                                this.dialogVisible = false;
                            }
                            this.loading = false;
                        })
                        .catch((err) => {
                            this.loading = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                } else {
                    params = {
                        phone: this.formLabelAccount.phone,
                        name: this.formLabelAccount.nickName,
                        password: this.formLabelAccount.password
                    };
                    this.$http.post('api/common/buildChildAccount', params)
                        .then((result) => {
                            if (result.code == 200) {
                                this.$message.success(result.msg);
                                this.getChildrenAccountList();
                                this.dialogVisible = false;
                            }
                            this.loading = false;


                        })
                        .catch((err) => {
                            this.loading = false;
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }

            },
            onSearch() {
                this.searchStr = "?id=" + this.$route.params.id;
                if (this.searchForm.phoneOrName) {
                    this.addConStr();
                    this.searchStr+=`phone=${this.searchForm.phoneOrName}`;
                }
                this.getChildrenAccountList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            }
        }
    }
</script>
<style lang="less">

    .children-account{
        .el-dialog__header {
            text-align: center !important;
        }

    }
</style>
<style scoped>
    .path-info {
        padding-bottom: 20px;
    }

    .orders-box {
        padding: 23px 17px;
        background-color: #fff;
        border-radius: 4px;
    }
</style>